package com.example.client_group5;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.ls.LSInput;

import android.net.Uri;

import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.BackgroundColorSpan;
import android.util.Log;
import android.view.Display;

import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.BufferType;


import android.app.Activity;

import android.content.Context;
import android.content.Intent;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;



public class TestActivity extends Activity implements OnClickListener{
	//private EditText contentEditText;
	private String content = "";
	private View tweetBt;
	private Intent pictureActionIntent = null;
	private String[] replyInfo;
	
	private Button cameraBt;
	private Button photoBt;
	private Button mentionBt;
	private static String encodePhoto;
	private final int CAMERA_PICTURE = 1;
    private final int GALLERY_PICTURE = 2;
    private ImageView photo;
    private Bitmap photoBitmap;
    private TextView numCharacterText;
    private EditText editText;
    private ListView listView;
    private boolean isSuggest = false;
    private ArrayList<SuggestUser> list;
    private UserSuggestAdapter adapter;
    private int offset;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_test);
        
        Bundle b = getIntent().getExtras();
        replyInfo = b.getStringArray("reply");
        numCharacterText = (TextView)findViewById(R.id.num_text_id);
        editText = (EditText)findViewById(R.id.edit_content);
  
        
        tweetBt = (View) findViewById(R.id.tweetAction);
        cameraBt=(Button)findViewById(R.id.camera_id);
        photoBt=(Button)findViewById(R.id.photo_id);
        photo=(ImageView)findViewById(R.id.photo_img);
        mentionBt = (Button)findViewById(R.id.mention_id);
        UserManager userProfile = new UserManager(this, "USER");
        ImageView avatar = (ImageView)findViewById(R.id.avatar_id);
        avatar.setImageBitmap(getBitmap(userProfile.getAvatar("avatar", "")));
        TextView username = (TextView)findViewById(R.id.username_id);
        username.setText(userProfile.getUserName("username", ""));
        cameraBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(pictureActionIntent, CAMERA_PICTURE);			
			}
		});
        photoBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
					pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
	                pictureActionIntent.setType("image/*");
	                pictureActionIntent.putExtra("return-data", true);
	                startActivityForResult(pictureActionIntent, GALLERY_PICTURE);
			}
		});
       
		if(replyInfo.length == 2){
			editText.append("\"" + replyInfo[1].substring(0, replyInfo[1].length() - 1) + "\"");
			numCharacterText.setText("" + (140 - replyInfo[1].length()));
			tweetBt.setEnabled(true);
			tweetBt.setBackgroundResource(R.drawable.tweet_button);
		}
		if(replyInfo.length > 2){
			String replyUser = "";
			int start = 0;
			for(int i = 1; i < replyInfo.length; i ++){
				if(i != 2){
					if(i == 1){
						replyUser += "@" + replyInfo[1] + " ";
						start = replyUser.length();
					}
					else{
						if(!replyInfo[i].equals("@" + replyInfo[1])){
							replyUser += replyInfo[i] + " ";
						}
					}
				}
			}
			numCharacterText.setText("" + (140 - replyInfo[1].length()));
			tweetBt.setEnabled(true);
			tweetBt.setBackgroundResource(R.drawable.tweet_button);
			
			SpannableString text = new SpannableString(replyUser);
			Log.d("tag", "start: " + start);
			if(start < replyUser.length()){
				text.setSpan(new BackgroundColorSpan(Color.YELLOW), start, replyUser.length(), 0);
				editText.setText(text, BufferType.SPANNABLE);
			}
			else
				editText.append(replyUser);
		}
		listView = (ListView)findViewById(R.id.list_suggest);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(list != null){
					isSuggest = false;
					SuggestUser user = list.get(arg2);
					String currentText = editText.getText().toString();
					String afterText = "";
					if(offset + 1 <= currentText.length())
						afterText = currentText.substring(0, offset + 1) + user.username + " ";
					editText.setText(afterText);
					listView.setVisibility(View.GONE);
					
				}
			}
		});
		list = new ArrayList<SuggestUser>();
		
		editText.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
				Log.d("tag", "start: " + start + "/before: " + before + "/count: " + count + "offset: " + offset + "length: " + s.length());
				int remain = 140 - editText.getText().toString().length();
				if(remain < 0 || remain == 140){
					tweetBt.setEnabled(false);
					tweetBt.setBackgroundResource(R.drawable.tweet_invi_button);
				}
				else{
					if(!tweetBt.isEnabled()){
						tweetBt.setEnabled(true);
						tweetBt.setBackgroundResource(R.drawable.tweet_button);
					}
				}
				numCharacterText.setText("" + remain);
				if(isSuggest){
					if(s.length() >= (offset + 1)){
						list = userSuggest(s.toString().substring(offset + 1).trim());
						adapter = new UserSuggestAdapter(TestActivity.this, R.layout.listsuggest, list);
						listView.setAdapter(adapter);
						Log.d("tag", "FUCK        YOU");
					}
				}
				char c = 'z';
				if(before == 0){
					c = s.charAt(start);
					if(c == ' '){
						if(isSuggest){
							isSuggest = false;
							listView.setVisibility(View.GONE);
						}
					}
					if(c == '@'){
						isSuggest = true;
						listView.setVisibility(View.VISIBLE);
						offset = start;
					}
				}
				if(before == 1){
					// start = length
					if(start > 0 && !isSuggest){
						for(int i = start - 1; i >= 0; i --){
							c = s.charAt(i);
							Log.d("character", "current character: " + c);
							if(c == '@'){
								offset = i;
								isSuggest = true;
								listView.setVisibility(View.VISIBLE);
								Log.d("offset", "Offset: " + offset);
								break;
							}
							if(c == ' '){
								isSuggest = false;
								break;
							}
						}
					}
				}	
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		tweetBt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(tweetBt.isEnabled()){
					content = editText.getText().toString();
					String tweet_id = "";
					
					if(replyInfo.length > 2){
			        	tweet_id = replyInfo[0];
			        }
					
					//new TweetTask().execute(tweet_id);
					postData(tweet_id);
				}
			}
		});
        mentionBt.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
//				contentEditText.append(" @");
				editText.append("@");
//				isSuggest = true;
//				listView.setVisibility(View.VISIBLE);
			}
		});
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {	  
    	if (keyCode == KeyEvent.KEYCODE_BACK) {
    		Intent i = new Intent(this, LazyLoading.class);
			startActivity(i);
			finish();
			
			return true;
			     
		}
		return false;
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
	public void postData(String tweet_id){

		try{
			//HttpClient hc=new DefaultHttpClient();  
    		ResponseHandler <String> res=new BasicResponseHandler();  
    		// 10.0.2.2
    		String postUrl = "";
    		if(tweet_id.equals(""))
    			postUrl = Setting.ipServer + "api/tweet/tweet" ;
    		else
    			postUrl = Setting.ipServer + "api/tweet/tweet?tweet_id=" + tweet_id;
    		
    		HttpPost postMethod=new HttpPost(postUrl);  
    		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);    
    		nameValuePairs.add(new BasicNameValuePair("content", content.trim()));    
    		if(encodePhoto!=null)
    		{
    			nameValuePairs.add(new BasicNameValuePair("image", encodePhoto));	
    			Log.d("tag", "" + content+";encode:"+encodePhoto);
    		}
    		postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));  
    		
    		//String response = hc.execute(postMethod,res); 
    		String response = SignInActivity.client.execute(postMethod,res); 
    		
    		Log.d("AAA", "TRA VE: " + response);
    		JSONObject jsonObject = null;
    		jsonObject = new JSONObject(response);
    		Object result = jsonObject.get("isSuccess");
    		if(result.toString().equals("true")){
    			Intent i = new Intent(TestActivity.this, LazyLoading.class);
    			startActivity(i);
    			finish();
    		}
    		else{
    			Toast toast = Toast.makeText(TestActivity.this, "Server time out", Toast.LENGTH_LONG);
    			toast.show();
    		}
    		
    		
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GALLERY_PICTURE) {
            if(data != null){
        		 Uri selectedImage = data.getData();
	             String[] filePathColumn = {MediaStore.Images.Media.DATA};
	
	             Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	             cursor.moveToFirst();
	
	             int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	             String filePath = cursor.getString(columnIndex);
	             cursor.close();
	             File file=new File(filePath);
	             this.photoBitmap = decodeFile(file);
	             
	             photo.setImageBitmap(photoBitmap);
	             editText.setPadding(5, 0, 50, 0);
	             ByteArrayOutputStream encodeStream=new ByteArrayOutputStream();
	             photoBitmap.compress(Bitmap.CompressFormat.JPEG,90, encodeStream);
	             byte [] encodeByte=encodeStream.toByteArray();
	             TestActivity.encodePhoto=Base64.encodeBytes(encodeByte);
	            // Log.d("encode","img:"+encodeString);
	             cursor.close();
        	 }
        	 else{
        		 Toast toast = Toast.makeText(this, "No Image is selected.", Toast.LENGTH_LONG);
                 toast.show();
        	 }
        }
        else if (requestCode == CAMERA_PICTURE) {
            if (data!= null) {
                // here is the image from camera
            	this.photoBitmap = (Bitmap) data.getExtras().get("data");
                photo.setImageBitmap(photoBitmap);
                ByteArrayOutputStream encodeStream=new ByteArrayOutputStream();
	             photoBitmap.compress(Bitmap.CompressFormat.JPEG,90, encodeStream);
	             byte [] encodeByte=encodeStream.toByteArray();
	             TestActivity.encodePhoto=Base64.encodeBytes(encodeByte);
            }
            else{
       		 Toast toast = Toast.makeText(this, "No Image is selected.", Toast.LENGTH_LONG);
                toast.show();
       	 }
        }
    }
	public Bitmap getBitmap(String bitmapUrl) {
		try {
			URL url = new URL(bitmapUrl);
		    return BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
		}
		catch(Exception ex) {return null;}
	}
	private Bitmap decodeFile(File f) {
        try {
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale++;
            }

            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        }
        catch (FileNotFoundException e) {
        }
        return null;
    }
	public ArrayList<SuggestUser> userSuggest(String character){
		ArrayList<SuggestUser> suggestList = new ArrayList<SuggestUser>();
		
		String url = Setting.ipServer + "api/user/mentions?u=" + character;
		Log.d("tag", url);
		
		HttpGet get = new HttpGet(url);
		 
		ResponseHandler<String> responseHandler = 
		        new BasicResponseHandler();

		String responseBody = null;
		try {
		    responseBody = SignInActivity.client.execute(get, responseHandler);
		    
		} catch(Exception ex) {
			  ex.printStackTrace();
		}
	
		Log.d("tag", "Tra ve: " + responseBody);
		try {
			JSONArray array = new JSONArray(responseBody);
			for(int i = 0; i < array.length(); i ++){
				JSONObject t = (JSONObject)array.get(i);
				String profile_img = t.getString("avatar");
				String fullname = t.getString("fullname");
				String username = t.getString("username");
				SuggestUser user = new SuggestUser("", profile_img, fullname, username);
				suggestList.add(user);
				//Log.d("tag", list[i]);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return suggestList;
	}
	private class UserSuggestAdapter extends ArrayAdapter<SuggestUser> {
		private ArrayList<SuggestUser> suggestList;

		public UserSuggestAdapter(Context context, int textViewResourceId, ArrayList<SuggestUser> suggestList) {
			super(context, textViewResourceId, suggestList);
			this.suggestList = suggestList;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.listsuggest, null);
			}
			SuggestUser user = (suggestList).get(position);
			if (user != null) {
				ImageView avatar = (ImageView)v.findViewById(R.id.profile_id);
				TextView fullname = (TextView)v.findViewById(R.id.fullname);
				TextView username = (TextView)v.findViewById(R.id.username);
				if(avatar != null){
					avatar.setImageBitmap(getBitmap(user.profile_img));
				}
				if(fullname != null){
					fullname.setText(user.fullname);
				}
				if(username != null){
					username.setText("@" + user.username);
				}
			}
			
			return v;
		}
	}
	
	
}
